{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "import backtrader as bt\n",
    "from backtrader_wrap import single_symbol_spot_backtest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>open</th>\n",
       "      <th>high</th>\n",
       "      <th>low</th>\n",
       "      <th>close</th>\n",
       "      <th>volume</th>\n",
       "      <th>close_datetime</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>datetime</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2021-01-01 00:00:00+00:00</th>\n",
       "      <td>28923.63</td>\n",
       "      <td>29017.50</td>\n",
       "      <td>28690.17</td>\n",
       "      <td>28752.80</td>\n",
       "      <td>2.423972e+07</td>\n",
       "      <td>2021-01-01 00:14:59.999000+00:00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-01 00:15:00+00:00</th>\n",
       "      <td>28752.80</td>\n",
       "      <td>28875.55</td>\n",
       "      <td>28720.91</td>\n",
       "      <td>28836.63</td>\n",
       "      <td>1.384695e+07</td>\n",
       "      <td>2021-01-01 00:29:59.999000+00:00</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2021-01-01 00:30:00+00:00</th>\n",
       "      <td>28836.63</td>\n",
       "      <td>28943.87</td>\n",
       "      <td>28836.62</td>\n",
       "      <td>28930.11</td>\n",
       "      <td>1.361619e+07</td>\n",
       "      <td>2021-01-01 00:44:59.999000+00:00</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                               open      high       low     close  \\\n",
       "datetime                                                            \n",
       "2021-01-01 00:00:00+00:00  28923.63  29017.50  28690.17  28752.80   \n",
       "2021-01-01 00:15:00+00:00  28752.80  28875.55  28720.91  28836.63   \n",
       "2021-01-01 00:30:00+00:00  28836.63  28943.87  28836.62  28930.11   \n",
       "\n",
       "                                 volume                   close_datetime  \n",
       "datetime                                                                  \n",
       "2021-01-01 00:00:00+00:00  2.423972e+07 2021-01-01 00:14:59.999000+00:00  \n",
       "2021-01-01 00:15:00+00:00  1.384695e+07 2021-01-01 00:29:59.999000+00:00  \n",
       "2021-01-01 00:30:00+00:00  1.361619e+07 2021-01-01 00:44:59.999000+00:00  "
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "symbol = \"BTCUSDT\"\n",
    "data_folder = \"../binance_klines/1m\"\n",
    "dataframe_1m = pd.read_parquet(\n",
    "    os.path.join(data_folder, f\"{symbol}.parquet\"))[\n",
    "        [\"open\", \"high\", \"low\", \"close\", \"volume\", \"close_datetime\"]]\n",
    "\n",
    "# 针线往往发生在极短的时间中,所以只需在短周期的k线\n",
    "ohlcv_dict = {                                                                                                             \n",
    "    'open': 'first',                                                                                                    \n",
    "    'high': 'max',                                                                                                       \n",
    "    'low': 'min',                                                                                                        \n",
    "    'close': 'last',                                                                                                    \n",
    "    'volume': 'sum',\n",
    "    'close_datetime': 'max',\n",
    "}\n",
    "\n",
    "dataframes = {\"1m\": dataframe_1m}\n",
    "for i in range(2, 16):\n",
    "    dataframes[f\"{i}m\"] = dataframe_1m.resample(f\"{i}min\").agg(ohlcv_dict)\n",
    "dataframes[\"15m\"].head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ReceiveNeedle(bt.Strategy):\n",
    "    params = (\n",
    "        (\"ratio\", None),\n",
    "    )\n",
    "\n",
    "    def __init__(self, ):\n",
    "        self.data_close = self.datas[0].close\n",
    "        self.needle = bt.talib.\n",
    "\n",
    "    def next(self):\n",
    "        position = self.getposition(self.datas[0]).size\n",
    "\n",
    "        # 金叉：短期均线越过长期均线，索引0始终指向当前天\n",
    "        if self.sma_short[0] > self.sma_long[0] and self.sma_short[-1] < self.sma_long[-1]:\n",
    "            # 没有持仓该币种，则半仓市价买入\n",
    "            # 市价单或限价单\n",
    "            if position == 0:\n",
    "                self.amount = self.broker.getcash() / 2.0 / self.data_close[0]\n",
    "                self.order = self.buy(size=self.amount)\n",
    "                \n",
    "        # 死叉：短期均线跌过长期均线，索引-1指向前一天\n",
    "        if self.sma_short[0] < self.sma_long[0] and self.sma_short[-1] > self.sma_long[-1]:\n",
    "            # 持仓了该币种，则全部卖出\n",
    "            if position > 0:\n",
    "                self.sell(size=position)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "3aba466d98760e10f57c547ae8ef48ed865b6c839ce75ea251de90807d1dd24d"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
